package com.easy.stock.dao;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jongo.Jongo;
import org.jongo.MongoCollection;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import com.mongodb.DB;
import com.mongodb.MongoClient;

public class MongoDataSource implements InitializingBean, DisposableBean {
	
	private static Log LOG = LogFactory.getLog("dao");
	
	private String host;
	private int port;
	private MongoClient mongoClient;
	
	public void afterPropertiesSet() throws Exception {
		mongoClient = new MongoClient(host, port);
		LOG.info("initialize mongo client success!");
	}
	
	public void destroy() throws Exception {
		if(mongoClient!=null)
			mongoClient.close();
	}
	
	
	public MongoClient getClient() {
		return mongoClient;
	}
	
	public MongoCollection getCollection(String dbName, String collectionName) {
		DB db = mongoClient.getDB(dbName);
		Jongo jongo = new Jongo(db);
		MongoCollection collection = jongo.getCollection(collectionName);
		return collection;
	}
	
	
	public void setHost(String host) {
		this.host = host;
	}

	public void setPort(int port) {
		this.port = port;
	}

}
